#include <iostream>
#include "sock.hpp"
#include "protocol.hpp"

using namespace ns_protocol;

static void Usage(const std::string proc)
{
    std::cout << "\nUsage: " << proc << " server_ip, server port\n"
              << std::endl;
}

int main(int argc, char *argv[])
{

    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);
    Sock sock;
    int sockfd = sock.Socket();
    if (!sock.Connect(sockfd, server_ip, server_port))
    {
        std::cerr << "Connect error" << std::endl;
        exit(2);
    }

    bool quit = false;
    std::string buff;
    while (!quit)
    {
        Request req;
        std::cout << "Please enter x:", std::cin >> req._x;
        std::cout << "Please enter y:", std::cin >> req._y;
        std::cout << "Please enter operate:", std::cin >> req._op;
        // 2、序列化
        std::string s = req.Serialize();
        // 3、添加长度报头
        s = Encode(s);
        // 4、发送
        Send(sockfd, s);
        // 5、读取
        while (true)
        {
            bool res = Recv(sockfd, &buff);
            if (!res)
            {
                quit = true;
                break;
            }
            std::string package = Decode(buff);
            if (package.empty())
                continue;

            Response resp;
            resp.Deserialize(package);
            std::cout << "code: " << resp._code << std::endl;
            std::cout << "result: " << resp._result << std::endl;
            // sleep(1);
            break;
        }
    }

    close(sockfd);

    return 0;
}